Imports MIMS.WRS.Business
Imports MIMS.WRS.Entities
Imports System.IO
Imports MyFramework
Imports System.Xml

Public Class IMStockReport
    Inherits System.Web.UI.Page

    Protected WithEvents header As StockReportHeader
    Protected WithEvents lblMessage As System.Web.UI.WebControls.Label

    Private territory As Territory = Nothing


#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents dlReport As System.Web.UI.WebControls.DataList

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Protected Function VisibleDescription2(ByVal data As Object) As String
        If data Is DBNull.Value OrElse Convert.ToString(data).Trim() = "" Then
            Return "display:none"
        Else
            Return ""
        End If
    End Function

    Protected Function GetMinOrderQtyValue(ByVal data As Object) As String
        Dim value As String = ""
        If data Is DBNull.Value Then
            value = ""
        Else
            Dim minOrderQtyValue As Integer = 0
            Try
                minOrderQtyValue = Convert.ToInt32(data)
            Catch ex As Exception
            End Try
            If (minOrderQtyValue > 0) Then
                value = minOrderQtyValue.ToString() & " "
            End If
        End If
        Return value
    End Function

    Protected Function GetTerritory() As String
        If (territory Is Nothing) Then
            territory = TerritoryService.GetTerritory(RequestContext.TerritoryID)
        End If

        If Not (territory Is Nothing) Then
            Return territory.Description
        Else
            Return ""
        End If
    End Function

    Protected Function GetPackType2Text(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackType2Meaning(Convert.ToString(data))
        End If
    End Function

    Protected Function GetPackTypeText(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Return BulkOrder.GetBOPackTypeMeaning(Convert.ToString(data))
        End If
    End Function

    Protected Function GetQtyAvailHTML(ByVal container As Object) As String
        Dim bo As BulkOrderEx = CType(container, BulkOrderEx)
        'Dim qtyAvail As Integer = bo.QuantityAvailable        
        'Dim packQty As Integer = bo.PackQty ' also is LGDCatPackQty

        'Dim isShownInLGD As Boolean = bo.IsShownInLGDCatalog

        Try
            If (bo.IDSQuantityAvail <> Nulls.NullInteger) Then
                Return bo.IDSQuantityAvail.ToString()
            Else
                Return "&nbsp;"
            End If
        Catch ex As Exception
            Return "&nspb;"
        End Try

    End Function

    Protected Function GetQtyAvailDesc(ByVal container As Object) As String
        Dim bo As BulkOrder = CType(container, BulkOrder)
        Dim qtyAvail As Integer = bo.QuantityAvailable
        Dim catPackDesc As String = bo.CatPackDesc
        Dim packQty As Integer = bo.PackQty ' also is LGDCatPackQty
        Dim unitDesc As String = bo.Pack

        Dim isShownInLGD As Boolean = bo.IsShownInLGDCatalog

        If (isShownInLGD = True) Then
            'Logger.Debug("packQty: " + packQty.ToString())
            'Logger.Debug("catPackDesc: " + catPackDesc)
            'Logger.Debug("GetPackType2Text: " + GetPackType2Text(catPackDesc))
            If packQty <> Nulls.NullInteger Then
                Return GetPackType2Text(catPackDesc)
            Else
                Return "&nbsp;"
            End If
        Else
            If qtyAvail <> Nulls.NullInteger Then
                Return GetPackTypeText(unitDesc)
            Else
                Return "&nbsp;"
            End If
        End If
    End Function

    Protected Function GetPackTypeTextNotNull(ByVal data As Object, ByVal pack As Object) As String

        If data Is DBNull.Value OrElse Convert.ToString(data).Trim.Length = 0 Then
            Return "&nbsp;"
        Else
            Dim dummy As Integer = 0
            Try
                dummy = Convert.ToInt32(data)
            Catch ex As Exception

            End Try
            If dummy = Nulls.NullInteger Then
                Return "&nbsp;"
            Else
                Return GetPackTypeText(pack)
            End If
        End If
    End Function

    Protected Function GetFOB(ByVal data As Object, ByVal unitDesc As String, ByVal obj As Object) As String
        If data Is DBNull.Value Or Convert.ToDecimal(data) = Nulls.NullDecimal Then
            Return "&nbsp;"
        Else
            Dim bo As BulkOrder = CType(obj, BulkOrder)
            Dim unitFOBPrice As String = ""
            Dim discountPercentage As Decimal

            If (Convert.ToDecimal(data) = 0D) Then
                unitFOBPrice = "0.00"
            ElseIf (bo.SpecialOfferDisc = Nulls.NullDecimal OrElse bo.SpecialOfferDisc = 0) Then
                unitFOBPrice = (Convert.ToDecimal(data) * (1 - RequestContext.Discount / 100)).ToString(Config.DecimalFormat)
            Else
                discountPercentage = RequestContext.Discount + bo.SpecialOfferDisc
                unitFOBPrice = (Convert.ToDecimal(data) * (1 - discountPercentage / 100)).ToString(Config.DecimalFormat)
            End If

            If (bo.SpecialOfferDisc = Nulls.NullDecimal OrElse bo.SpecialOfferDisc = 0) Then
                Return String.Format("{0} (USD) per {1}", _
               unitFOBPrice, _
               BulkOrder.GetBOPackTypeMeaning(unitDesc))
            Else
                Return String.Format("<span class='SpecialOffer'>{0} (USD) per {1}<br>SPECIAL PRICE, {2}% Discount included.</span>", _
                          unitFOBPrice, _
                            BulkOrder.GetBOPackTypeMeaning(unitDesc), discountPercentage.ToString("#######"))
            End If
        End If
    End Function

    Protected Function GetPictureHTML(ByVal data As Object) As String
        If data Is DBNull.Value Then
            Return "&nbsp;"
        Else
            Dim filePath As String = String.Format("{0}.jpg", Path.Combine(Config.ProductImagePath, Convert.ToString(data)))

            If File.Exists(filePath) Then
                Return String.Format("<img src='../Offices/ViewPicture.aspx?procode={0}&size={1}' border=0 alt='{0}.jpg'>", data, Config.BOSalesReportImageSize)
            Else
                Return "&nbsp;"
            End If
        End If
    End Function

    Protected Function GetReservedQtyText(ByVal container As Object) As String
        Dim qty As Integer = 0
        Dim pack As String = GetPackTypeText(DataBinder.Eval(container, "DataItem.Pack"))
        Try
            qty = Convert.ToInt32(DataBinder.Eval(container, "DataItem.QuantityReserved"))
        Catch ex As Exception

        End Try

        If (qty > 0) Then
            Return String.Format("{0} {1} of the quantity shown are currently under offer", qty, pack)
        Else
            Return ""
        End If

    End Function

    Protected Function GetCatalogPageHTML(ByVal container As Object) As String
        Dim catalog As Object = DataBinder.Eval(container, "DataItem.CatalogName")
        If ((Not (catalog Is DBNull.Value)) AndAlso Convert.ToString(catalog).ToUpper.StartsWith("LGD") _
            AndAlso Convert.ToString(DataBinder.Eval(container, "DataItem.Page")).Trim().Length > 0) Then
            Return String.Format("<td width='1%' nowrap>Catalogue Page:</td><td>{0}</td>", DataBinder.Eval(container, "DataItem.Page"))
        Else
            Return ""
        End If
    End Function

    Protected Function GetClearanceStockHTML(ByVal container As Object) As String
        Dim _idsSort As String = Convert.ToString(DataBinder.Eval(container, "DataItem.IDSSort"))
        If (_idsSort.Trim().ToUpper() = "CLEARANCE STOCK") Then
            Return String.Format("<br><font color='red'>{0}</font>", "Clearance Stock - Priced to Clear !")
        Else
            Return ""
        End If
    End Function

    Private Function GetSource() As BulkOrderCollection
        Return BulkOrderService.GetBulkOrdersIDSReport(RequestContext.ConPointID, RequestContext.CurrentUser.LOGIN_NAME, _
            Convert.ToInt32(Request.QueryString("sort")), RequestContext.Quantity, Convert.ToInt32(Request.QueryString("ownerid")), RequestContext.CurrentUser.US_ID_PK, RequestContext.TerritoryID)
    End Function

#Region " Product Dimensions"
    Private Function MeasurementUnit() As String
        If (ViewState("MeasurementUnit") Is Nothing) Then
            Dim countryObj As New Country
            countryObj = CountryService.GetCountry(RequestContext.CurrentUser.CountryID)
            If (countryObj Is Nothing) Then
                ViewState("MeasurementUnit") = ""
            Else
                ViewState("MeasurementUnit") = countryObj.MeasUnit
            End If
        End If
        Return Convert.ToString(ViewState("MeasurementUnit"))
    End Function

    Dim measuredUnit As String = "(inches)"
    Public Function GetUnit() As String
        If (MeasurementUnit() = "Metric") Then
            measuredUnit = "(cm)"
        Else
            measuredUnit = "(inches)"
        End If
        If ((Not RequestContext.CurrentUser Is Nothing AndAlso RequestContext.CurrentUser.IS_ADMIN)) Then
            measuredUnit = "(cm)"
        End If
        Return measuredUnit
    End Function

    Public Function GetUnit2() As String 'each item just accessed DB 1 time, first usage is invoked GetUnit() 
        Return measuredUnit
    End Function

    Public Function GetDimension(ByVal data As Object) As String
        If (data Is DBNull.Value) Then
            Return ""
        Else
            Dim decValue As Decimal = Convert.ToDecimal(data)
            If (decValue = Nulls.NullDecimal) Then
                Return ""
            Else
                If (decValue = 0.0) Then
                    Return ""
                End If
                If (measuredUnit = "(inches)") Then
                    decValue = decValue / Convert.ToDecimal(2.54)
                    If (decValue < 1) Then
                        Return "0" + decValue.ToString(Config.DecimalFormatEx)
                    End If
                End If
                Return decValue.ToString(Config.DecimalFormatEx)
            End If
        End If
    End Function

    Public Function GetTextByProductRound(ByVal data As Object, ByVal container As Object) As String
        Dim productRoud As Boolean = True
        Dim bo As BulkOrderEx = CType(container, BulkOrderEx)
        If (Not data Is DBNull.Value) Then
            productRoud = Convert.ToBoolean(data)
        End If
        If (Not productRoud AndAlso bo.DimensionID > 0) Then
            Return "Length"
        End If
        Return "Dia"
    End Function

    Private Function DecValue(ByVal value As Decimal) As String
        If (value = Nulls.NullDecimal) Then
            Return ""
        Else
            If (value = 0.0) Then
                Return ""
            End If
            If (measuredUnit = "(inches)") Then
                value = value / Convert.ToDecimal(2.54)
                If (value < 1) Then
                    Return "0" + value.ToString(Config.DecimalFormatEx)
                End If
            End If
            Return value.ToString(Config.DecimalFormatEx)
        End If
    End Function

    Public Function ViewRowIfIsProductRound(ByVal data As Object, ByVal container As Object) As String
        Dim sbText As New System.Text.StringBuilder
        Dim bo As BulkOrderEx = CType(container, BulkOrderEx)
        Dim productRoud As Boolean = True
        If (Not data Is DBNull.Value) Then
            productRoud = Convert.ToBoolean(data)
        End If
        If (Not productRoud AndAlso bo.DimensionID > 0) Then
            sbText.AppendFormat("<td width='24%' nowrap>Width {0}</td>", GetUnit()) 'sbText.AppendFormat("<tr><td width='24%' nowrap>Width {0}</td>", GetUnit())
            'sbText.Append("<td><table class='OrderReport' cellpadding='0' cellspacing='0'width='90%' height='5px' style='table-layout:fixed'><tr>")
            sbText.AppendFormat("<td>{0}</td>", DecValue(bo.WidthS1))
            sbText.AppendFormat("<td>{0}</td>", DecValue(bo.WidthS2))
            sbText.AppendFormat("<td>{0}</td>", DecValue(bo.WidthS3))
            sbText.AppendFormat("<td>{0}</td>", DecValue(bo.WidthS4))
            sbText.AppendFormat("<td>{0}</td>", DecValue(bo.WidthS5))
            sbText.AppendFormat("<td>{0}</td>", DecValue(bo.WidthS6))
            sbText.AppendFormat("<td>{0}</td>", DecValue(bo.WidthS7))
            sbText.AppendFormat("<td>{0}</td>", DecValue(bo.WidthS8))
            'sbText.Append("</tr></table></td></tr>")
        End If
        Return sbText.ToString()
    End Function

    Public Function GetTextByProductRound(ByVal bo As BulkOrderEx) As String
        If (Not bo.IsProductRound AndAlso bo.DimensionID > 0) Then
            Return "Length"
        End If
        Return "Dia"
    End Function

    Public Function DisplayBaseOnMaxMeasurementNumber(ByVal container As Object) As String
        Dim bo As BulkOrderEx = CType(container, BulkOrderEx)
        Dim sbTextForTitleRow As New System.Text.StringBuilder
        Dim sbTextForDiaOrLengthRow As New System.Text.StringBuilder
        Dim sbTextForWidthRow As New System.Text.StringBuilder
        Dim sbTextForHeightRow As New System.Text.StringBuilder
        Dim measurementUnit As String = GetUnit()
        Dim bWidth As Boolean = (Not bo.IsProductRound AndAlso bo.DimensionID > 0)
        Dim iCount As Integer = 0
        'BEGIN TAG
        sbTextForDiaOrLengthRow.AppendFormat("<tr><td width='36%' nowrap>{0} {1}:</td>", GetTextByProductRound(bo), measurementUnit)
        If (bWidth) Then
            sbTextForWidthRow.AppendFormat("<tr><td width='36%' nowrap>Width {0}:</td>", measurementUnit)
        End If
        sbTextForHeightRow.AppendFormat("<tr><td width='36%' nowrap>Height {0}:</td>", measurementUnit)

        Dim bHasValue As Boolean = False
        If Not (bo.DiaOrLenS1 = Nulls.NullDecimal OrElse bo.DiaOrLenS1 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.HeightS1 = Nulls.NullDecimal OrElse bo.HeightS1 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.WidthS1 = Nulls.NullDecimal OrElse bo.WidthS1 = 0.0) Then
            bHasValue = True
        End If
        If (bHasValue) Then
            sbTextForTitleRow.AppendFormat("<td align='right'>S1</td>")
            sbTextForDiaOrLengthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.DiaOrLenS1))
            sbTextForWidthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.WidthS1))
            sbTextForHeightRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.HeightS1))
            bHasValue = False
            iCount += 1
        End If
        '-----------------------------------------------
        If Not (bo.DiaOrLenS2 = Nulls.NullDecimal OrElse bo.DiaOrLenS2 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.HeightS2 = Nulls.NullDecimal OrElse bo.HeightS2 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.WidthS2 = Nulls.NullDecimal OrElse bo.WidthS2 = 0.0) Then
            bHasValue = True
        End If
        If (bHasValue) Then
            sbTextForTitleRow.AppendFormat("<td align='right'>S2</td>")
            sbTextForDiaOrLengthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.DiaOrLenS2))
            sbTextForWidthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.WidthS2))
            sbTextForHeightRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.HeightS2))
            bHasValue = False
            iCount += 1
        End If
        '-----------------------------------------------
        If Not (bo.DiaOrLenS3 = Nulls.NullDecimal OrElse bo.DiaOrLenS3 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.HeightS3 = Nulls.NullDecimal OrElse bo.HeightS3 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.WidthS3 = Nulls.NullDecimal OrElse bo.WidthS3 = 0.0) Then
            bHasValue = True
        End If
        If (bHasValue) Then
            sbTextForTitleRow.AppendFormat("<td align='right'>S3</td>")
            sbTextForDiaOrLengthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.DiaOrLenS3))
            sbTextForWidthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.WidthS3))
            sbTextForHeightRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.HeightS3))
            bHasValue = False
            iCount += 1
        End If
        '-----------------------------------------------
        If Not (bo.DiaOrLenS4 = Nulls.NullDecimal OrElse bo.DiaOrLenS4 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.HeightS4 = Nulls.NullDecimal OrElse bo.HeightS4 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.WidthS4 = Nulls.NullDecimal OrElse bo.WidthS4 = 0.0) Then
            bHasValue = True
        End If
        If (bHasValue) Then
            sbTextForTitleRow.AppendFormat("<td align='right'>S4</td>")
            sbTextForDiaOrLengthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.DiaOrLenS4))
            sbTextForWidthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.WidthS4))
            sbTextForHeightRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.HeightS4))
            bHasValue = False
            iCount += 1
        End If
        '-----------------------------------------------
        If Not (bo.DiaOrLenS5 = Nulls.NullDecimal OrElse bo.DiaOrLenS5 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.HeightS5 = Nulls.NullDecimal OrElse bo.HeightS5 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.WidthS5 = Nulls.NullDecimal OrElse bo.WidthS5 = 0.0) Then
            bHasValue = True
        End If
        If (bHasValue) Then
            sbTextForTitleRow.AppendFormat("<td align='right'>S5</td>")
            sbTextForDiaOrLengthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.DiaOrLenS5))
            sbTextForWidthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.WidthS5))
            sbTextForHeightRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.HeightS5))
            bHasValue = False
            iCount += 1
        End If
        '-----------------------------------------------
        If Not (bo.DiaOrLenS6 = Nulls.NullDecimal OrElse bo.DiaOrLenS6 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.HeightS6 = Nulls.NullDecimal OrElse bo.HeightS6 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.WidthS6 = Nulls.NullDecimal OrElse bo.WidthS6 = 0.0) Then
            bHasValue = True
        End If
        If (bHasValue) Then
            sbTextForTitleRow.AppendFormat("<td align='right'>S6</td>")
            sbTextForDiaOrLengthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.DiaOrLenS6))
            sbTextForWidthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.WidthS6))
            sbTextForHeightRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.HeightS6))
            bHasValue = False
            iCount += 1
        End If
        '-----------------------------------------------
        If Not (bo.DiaOrLenS7 = Nulls.NullDecimal OrElse bo.DiaOrLenS7 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.HeightS7 = Nulls.NullDecimal OrElse bo.HeightS7 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.WidthS7 = Nulls.NullDecimal OrElse bo.WidthS7 = 0.0) Then
            bHasValue = True
        End If
        If (bHasValue) Then
            sbTextForTitleRow.AppendFormat("<td align='right'>S7</td>")
            sbTextForDiaOrLengthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.DiaOrLenS7))
            sbTextForWidthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.WidthS7))
            sbTextForHeightRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.HeightS7))
            bHasValue = False
            iCount += 1
        End If
        '-----------------------------------------------
        If Not (bo.DiaOrLenS8 = Nulls.NullDecimal OrElse bo.DiaOrLenS8 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.HeightS8 = Nulls.NullDecimal OrElse bo.HeightS8 = 0.0) Then
            bHasValue = True
        End If
        If Not (bo.WidthS8 = Nulls.NullDecimal OrElse bo.WidthS8 = 0.0) Then
            bHasValue = True
        End If
        If (bHasValue) Then
            sbTextForTitleRow.AppendFormat("<td align='right'>S8</td>")
            sbTextForDiaOrLengthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.DiaOrLenS8))
            sbTextForWidthRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.WidthS8))
            sbTextForHeightRow.AppendFormat("<td align='right'>{0}</td>", DecValue(bo.HeightS8))
            bHasValue = False
            iCount += 1
        End If

        'END TAG
        If (sbTextForTitleRow.Length > 0) Then
            sbTextForTitleRow.Insert(0, "<tr><td width='36%' nowrap>&nbsp;</td>")
            If (iCount > 0) Then
                For i As Integer = iCount + 1 To 8
                    sbTextForTitleRow.Append("<td>&nbsp;</td>")
                Next
            End If
            sbTextForTitleRow.Append("</tr>")
        End If

        If (iCount > 0) Then
            For i As Integer = iCount + 1 To 8
                sbTextForDiaOrLengthRow.Append("<td>&nbsp;</td>")
            Next
        End If
        sbTextForDiaOrLengthRow.Append("</tr>")

        If (bWidth) Then
            If (iCount > 0) Then
                For i As Integer = iCount + 1 To 8
                    sbTextForWidthRow.Append("<td>&nbsp;</td>")
                Next
            End If
            sbTextForWidthRow.Append("</tr>")
        Else
            sbTextForWidthRow = New System.Text.StringBuilder
        End If

        If (iCount > 0) Then
            For i As Integer = iCount + 1 To 8
                sbTextForHeightRow.Append("<td>&nbsp;</td>")
            Next
        End If
        sbTextForHeightRow.Append("</tr>")

        Dim result As String = ""

        result = String.Format("{0}{1}{2}{3}", sbTextForTitleRow.ToString(), sbTextForDiaOrLengthRow.ToString(), sbTextForWidthRow.ToString(), sbTextForHeightRow.ToString())

        Return result
    End Function

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AjaxPro.Utility.RegisterTypeForAjax(GetType(MIMS_WRS.Web.AjaxUtilMethod))

        If (Not IsPostBack) Then
            Dim cp As ConPoint = ConPointService.GetConPoint(RequestContext.ConPointID)
            If cp.IsDisplayed = False Then
                Throw New Exception("You are not allowed to view report of this consolidation point")
            End If

            If (RequestContext.DoReport) Then
                Dim source As BulkOrderCollection = GetSource()
                Dim found As Boolean = False
                If RequestContext.TerritoryID > -1 AndAlso RequestContext.ShowFOB = True Then
                    ' drill down source to find empty price 
                    For Each bo As BulkOrder In source
                        If (bo.FOB = Nulls.NullDecimal) Then
                            found = True
                            Exit For
                        End If
                    Next
                    If (found) Then
                        lblMessage.Text = "Contact your sales office to get missing Freight Paid (Home Delivered) prices"
                    End If
                End If

                lblMessage.Visible = found


                Dim customSource As BulkOrderExCollection = New BulkOrderExCollection
                Dim item As New BulkOrderEx
                Dim pd As New ProductDimensions
                For Each bo As BulkOrder In source
                    item = New BulkOrderEx
                    pd = BulkOrderService.GetProductDimensions(bo.BulkOrderID)
                    item = New BulkOrderEx(bo, pd)
                    customSource.Add(item)
                Next

                Me.dlReport.DataSource = customSource 'source
                Me.dlReport.DataBind()
            End If
        End If
    End Sub

    Private Sub header_ExportPDFClick() Handles header.ExportPDFClick

        'Dim source As BulkOrderCollection = GetSource()
        'Dim doc As XmlDocument = RenderService.GenerateBOXML(source, Config.ProductImagePath, RequestContext.Discount, RequestContext.ShowFOB)

        Dim customSource As BulkOrderExCollection = New BulkOrderExCollection
        Dim item As New BulkOrderEx
        Dim pd As New ProductDimensions
        Dim source As BulkOrderCollection = GetSource()
        For Each bo As BulkOrder In source
            item = New BulkOrderEx
            pd = BulkOrderService.GetProductDimensions(bo.BulkOrderID)
            item = New BulkOrderEx(bo, pd)
            customSource.Add(item)
        Next
        Dim doc As XmlDocument = RenderService.GenerateBOXMLEx(customSource, Config.ProductImagePath, RequestContext.Discount, RequestContext.ShowFOB, MeasurementUnit())

        Dim rootNode As XmlNode = doc.ChildNodes(0)
        Dim cp As ConPoint = ConPointService.GetConPoint(RequestContext.ConPointID)
        Dim node As XmlNode = doc.CreateElement("conpoint")
        node.AppendChild(RenderService.CreateCData(doc, cp.Description))
        rootNode.AppendChild(node)

        node = doc.CreateElement("containerloading")
        node.AppendChild(RenderService.CreateCData(doc, cp.ContainerLoading))
        rootNode.AppendChild(node)

        node = doc.CreateElement("loadingport")
        node.AppendChild(RenderService.CreateCData(doc, cp.LoadingPort))
        rootNode.AppendChild(node)



        Dim boXml As String = doc.OuterXml
        Dim xslFile As String = Server.MapPath("foxsl/fo.xsl")
        Dim foFile As String = Server.MapPath("foTemp/" + String.Format("{0}{1}{2}{3}{4}{5}{6}.fo", DateTime.Now.Year, _
                DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                DateTime.Now.Second, DateTime.Now.Millisecond))
        Dim pdfFile As String = String.Format("IMStockReport_{0}{1}{2}{3}{4}{5}{6}.pdf", DateTime.Now.Year, _
                DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                DateTime.Now.Second, DateTime.Now.Millisecond)
        Try
            If RenderService.GenerateFO(boXml, xslFile, foFile) Then
                Dim buffer() As Byte = RenderService.RenderFOtoPDF(foFile)
                File.Delete(foFile)

                Response.Clear()
                Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", HttpUtility.UrlEncode(pdfFile)))
                Response.AddHeader("Content-Type", "application/pdf")
                Response.BinaryWrite(buffer)
                Response.Flush()
                Response.End()

            End If
        Catch ex As Exception
            Logger.Debug("Failed to render BO SalesReport PDF", ex)
        End Try
    End Sub

    Private Sub header_OKClick1(ByVal conPointID As Integer, ByVal IDSSort As Integer, ByVal quantity As Integer, ByVal discount As Decimal, ByVal showFOB As Boolean, ByVal ownerId As Integer, ByVal territoryId As Integer, ByVal countryId As Integer) Handles header.OKClick
        Response.Redirect(String.Format("IMStockReport.aspx?discount={1}&showfob={2}&cpid={0}&sort={3}&qty={4}&dorpt=1&ownerid={5}&teid={6}&countryid={7}", _
                                conPointID, discount, Convert.ToInt32(showFOB), IDSSort, quantity, ownerId, territoryId, countryId))
    End Sub

    Private Sub dlReport_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles dlReport.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim ltrItemIndex As Literal = CType(e.Item.FindControl("ltrItemIndex"), Literal)
            ltrItemIndex.Text = (e.Item.ItemIndex + 1).ToString()

            Dim divAddingCart As HtmlGenericControl = CType(e.Item.FindControl("divAddingCart"), HtmlGenericControl)

            Dim lnkViewShoppingCart As LinkButton = CType(e.Item.FindControl("lnkViewShoppingCart"), LinkButton)

            Dim bulkOrderItem As BulkOrder
            bulkOrderItem = CType(CType(e.Item, DataListItem).DataItem, MIMS.WRS.Entities.BulkOrder)
            Dim selectedItem As String = Server.HtmlEncode(Server.HtmlDecode(GetShoppingItem(bulkOrderItem, (e.Item.ItemIndex + 1)))).Replace("'", Constants.QUOTE_SIGN)
            lnkViewShoppingCart.Attributes.Add("onclick", String.Format("javascript:AddToCart('{0}','{1}');return false;", selectedItem, divAddingCart.ClientID))
        End If
    End Sub

    Private Sub header_ViewShoppingCartClick1() Handles header.ViewShoppingCartClick
        Response.Redirect("ShoppingCartList.aspx")
    End Sub

    Dim selectedIndex As Integer = 0
    Protected Sub lnkViewShoppingCart_Command(ByVal sender As Object, ByVal e As CommandEventArgs)

        Try
            Dim source As LinkButton = DirectCast(sender, LinkButton)
            Dim dataItem As DataListItem = DirectCast(source.Parent, DataListItem)
            selectedIndex = dataItem.ItemIndex + 1
        Catch ex As Exception
        End Try
        Dim arrValues As String()
        Dim strArgument As String
        strArgument = DirectCast(e.CommandArgument, String)
        arrValues = strArgument.Split("@"c)
        AddItemToCard(arrValues)
    End Sub

    Private Sub AddItemToCard(ByVal arrValues As String())
        Dim oCollection As New Collection
        Dim bulkOrderId As Int32

        bulkOrderId = Convert.ToInt32(arrValues(6))
        Dim bSameTerritory As Boolean = True

        If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
            If (Not oCollection Is Nothing) Then
                For i As Integer = 1 To oCollection.Count
                    If (DirectCast(oCollection(i), ShoppingItem).BulkOrderId = bulkOrderId) Then
                        Dim scriptString As String = "<script language='JavaScript'> alert('You have already selected this item.');</script>"
                        Me.RegisterStartupScript("Startup", scriptString)
                        Return
                    End If

                    If (header.DeliveryAndPricingID = CType(DeliveryAndPricing.HD, String) And DirectCast(oCollection(i), ShoppingItem).TerritoryID <> "" And DirectCast(oCollection(i), ShoppingItem).TerritoryID <> header.TeritoryID) Then
                        bSameTerritory = False
                    End If
                Next
            End If
        End If
        If (bSameTerritory = False) Then
            Dim scriptString As String = "<script language='JavaScript'> alert('The item is not the same territory with previous selected items. View the shopping list for selected details. Please select others.');</script>"
            Me.RegisterStartupScript("Startup1", scriptString)
            Return
        End If
        Dim item As New ShoppingItem
        With item
            .ItemNo = Convert.ToInt32(IIf(selectedIndex = 0, oCollection.Count + 1, selectedIndex))
            .ProductCode = arrValues(0).ToString
            .Description = arrValues(1).ToString
            .Quantity = 1
            .UnitDesc = arrValues(2).ToString
            Try
                .UnitSettingID = Convert.ToInt32(arrValues(3))
            Catch ex As Exception
            End Try

            If arrValues(4).ToString.Length > 0 Then
                .UnitPrice = Convert.ToDouble(arrValues(4))
                .Total = .Quantity * .UnitPrice
            End If
            .UnitWeight = Convert.ToDecimal(arrValues(5))
            .Priority = -1
            .BulkOrderId = Convert.ToInt32(arrValues(6))
            If (header.DeliveryAndPricingID = CType(DeliveryAndPricing.HD, String)) Then
                .TerritoryID = header.TeritoryID
            End If

        End With

        oCollection.Add(item)
        Session(Constant.SS_SHOPPING_LIST) = oCollection
        Session("FOBorHD") = header.GetSelectedPriceType
        Session(Constant.SS_TERRITORY) = header.GetSelectedTeritory
    End Sub

    Protected Function ShoppingItem(ByVal container As Object, ByVal obj As Object) As String
        Dim bulkOrderId As Int32 = Convert.ToInt32(DataBinder.Eval(container, "DataItem.BulkOrderID"))
        Dim productCode As Object = DataBinder.Eval(container, "DataItem.ProductCode")
        Dim FOBDataItem As Object = DataBinder.Eval(container, "DataItem.FOB")
        Dim unitFOBPrice As Object = DataBinder.Eval(container, "DataItem.UnitFOBPrice")
        Dim strProductCode As String = ""
        Dim strDescription As String = ""
        Dim strUnit As String = ""
        Dim strUnitPrice As String = ""
        Dim unitSettingID As Integer = 0

        'Product Code
        If (productCode Is DBNull.Value) Then
            strProductCode = ""
        Else
            strProductCode = DirectCast(productCode, String)
        End If
        'Description
        strDescription = String.Format("{0} {1}", Utilities.GetNormalText(DataBinder.Eval(container, "DataItem.SalesDescription1")), Utilities.GetNormalText(DataBinder.Eval(container, "DataItem.Color")))
        'Unit
        Try

            If (Not DataBinder.Eval(container, "DataItem.UnitSettingID") Is DBNull.Value) Then
                unitSettingID = Convert.ToInt32(DataBinder.Eval(container, "DataItem.UnitSettingID"))
                strUnit = UnitSettingService.GetUnitSetting(unitSettingID).Description

            End If
        Catch ex As Exception
        End Try

        'Unit price
        If (RequestContext.ShowFOB) Then
            'If FOBDataItem Is DBNull.Value Or Convert.ToDecimal(FOBDataItem) = Nulls.NullDecimal Then
            '    strUnitPrice = ""
            'Else
            '    Dim bo As BulkOrder = CType(obj, BulkOrder)
            '    If (bo.SpecialOfferDisc = Nulls.NullDecimal OrElse bo.SpecialOfferDisc = 0) Then
            '        strUnitPrice = (Convert.ToDecimal(FOBDataItem) * (1 - RequestContext.Discount / 100)).ToString(Config.DecimalFormat)
            '    Else
            '        Dim discountPercentage As Decimal
            '        discountPercentage = RequestContext.Discount + bo.SpecialOfferDisc
            '        strUnitPrice = (Convert.ToDecimal(FOBDataItem) * (1 - discountPercentage / 100)).ToString(Config.DecimalFormat)
            '    End If
            'End If
            If unitFOBPrice Is DBNull.Value Or Convert.ToDecimal(unitFOBPrice) = Nulls.NullDecimal Then
                strUnitPrice = ""
            Else
                If (Convert.ToDecimal(unitFOBPrice) = 0D) Then
                    strUnitPrice = "0"
                Else
                    strUnitPrice = Convert.ToDecimal(unitFOBPrice).ToString(Config.DecimalFormat)
                End If

            End If

        Else
            strUnitPrice = GetDecimalValue(DataBinder.Eval(container, "DataItem.HomeDelivered15Price"))
        End If


        Return String.Format("{0}@{1}@{2}@{3}@{4}@{5}@{6}", strProductCode, strDescription, strUnit, unitSettingID, strUnitPrice, GetDecimalValue(DataBinder.Eval(container, "DataItem.UnitWeight")), bulkOrderId)

    End Function

    Protected Function GetShoppingItem(ByVal bulkOrderItem As BulkOrder, ByVal index As Integer) As String
        Dim bulkOrderId As Int32 = bulkOrderItem.BulkOrderID
        Dim productCode As Object = bulkOrderItem.ProductCode
        Dim FOBDataItem As Object = bulkOrderItem.FOB
        Dim unitFOBPrice As Object = bulkOrderItem.UnitFOBPrice
        Dim strProductCode As String = ""
        Dim strDescription As String = ""
        Dim strUnit As String = ""
        Dim strUnitPrice As String = ""
        Dim unitSettingID As Integer = 0
        Dim minQtyVolume As Decimal = 0

        'Product Code
        If (productCode Is DBNull.Value) Then
            strProductCode = ""
        Else
            strProductCode = DirectCast(productCode, String)
        End If
        'Description
        strDescription = String.Format("{0} {1} {2}", Utilities.GetNormalText(bulkOrderItem.SalesDescription1), Utilities.GetNormalText(bulkOrderItem.SalesDescription2), Utilities.GetNormalText(bulkOrderItem.Color))
        'Unit
        Try

            If (Not bulkOrderItem.UnitSettingID = Nulls.NullInteger) Then
                unitSettingID = bulkOrderItem.UnitSettingID
                strUnit = UnitSettingService.GetUnitSetting(unitSettingID).Description
            End If
        Catch ex As Exception
        End Try

        'Unit price
        If (header.DeliveryAndPricingID() = "-1") Then 'Value="-1": FOB ; Value="1": Freight Paid 
            If unitFOBPrice Is DBNull.Value Or Convert.ToDecimal(unitFOBPrice) = Nulls.NullDecimal Then
                strUnitPrice = ""
            Else
                If (bulkOrderItem.SpecialOfferDisc = Nulls.NullDecimal OrElse bulkOrderItem.SpecialOfferDisc = 0) Then
                    strUnitPrice = (Convert.ToDecimal(unitFOBPrice) * (1 - RequestContext.Discount / 100)).ToString(Config.DecimalFormat)
                Else
                    Dim discountPercentage As Decimal
                    discountPercentage = RequestContext.Discount + bulkOrderItem.SpecialOfferDisc
                    strUnitPrice = (Convert.ToDecimal(unitFOBPrice) * (1 - discountPercentage / 100)).ToString(Config.DecimalFormat)
                End If
            End If
        Else
            strUnitPrice = GetDecimalValue(bulkOrderItem.HomeDelivered15Price)
        End If
        minQtyVolume = bulkOrderItem.MinQtyVolume

        Dim minOrderQtyValue As Integer = bulkOrderItem.MinOrderQtyValue
        Return String.Format("{0}@{1}@{2}@{3}@{4}@{5}@{6}@{7}@{8}@{9}", strProductCode, strDescription, strUnit, unitSettingID, strUnitPrice, GetDecimalValue(bulkOrderItem.UnitWeight), bulkOrderId, minQtyVolume, index, minOrderQtyValue)

    End Function

    Public Shared Function GetDecimalValue(ByVal data As Object) As String
        If data Is DBNull.Value OrElse Convert.ToDecimal(data) = Nulls.NullDecimal Then
            Return "0"
        Else
            Return Convert.ToDecimal(data).ToString(Config.DecimalFormat)
        End If
    End Function

    Public Shared Function GetTextValue(ByVal data As Object) As String
        If data Is DBNull.Value OrElse Convert.ToString(data).Trim() = "" Then
            Return ""
        Else
            Return (Convert.ToString(data))
        End If
    End Function

    ' <asp:linkbutton id="lnkViewShoppingCart" Runat="server" OnCommand="lnkViewShoppingCart_Command" CommandName="AddToCard" CommandArgument='<%# ShoppingItem(Container,Container.DataItem) %>' >Add to Cart</asp:linkbutton> 
End Class
